using System.Security.Claims;
using AnQinFrameWorkAPI.Entity.Finance.DTO.FinanceLogin;
using AnQinFrameWorkAPI.Service.Finance;
using FrameWork.Request;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace AnQinFrameWorkAPI.Controllers.Finance;

/// <summary>
///     财务用户登录API
/// </summary>
[Route("api/[controller]")]
[ApiController]
[ApiExplorerSettings(GroupName = "Finance")]
public class FinanceUserLoginController : ControllerBase
{
    //业务接口
    private readonly FinanceUserLoginService _financeUserLoginService;

    //构造注入
    public FinanceUserLoginController(FinanceUserLoginService financeUserLoginService)
    {
        _financeUserLoginService = financeUserLoginService;
    }

    /// <summary>
    ///     财务用户登录
    /// </summary>
    [HttpPost("Login")]
    [ProducesResponseType(typeof(FinanceUserLoginResultDTO), 200)]
    public async Task<IActionResult> FinanceUserLogin([FromBody] FinanceUserLoginDTO loginDTO)
    {
        //获取客户端IP
        var ip = HttpContext.Connection.RemoteIpAddress?.ToString() ?? "unknown";
        //获取设备信息
        var userAgent = HttpContext.Request.Headers["User-Agent"].ToString();
        
        var response = await _financeUserLoginService.FinanceUserLogin(loginDTO, ip, userAgent);
        return StatusCode(response.Status, response);
    }

    /// <summary>
    ///     验证财务用户Token
    /// </summary>
    [HttpGet("Validate")]
    [Authorize]
    [ProducesResponseType(typeof(object), 200)]
    public async Task<IActionResult> ValidateToken()
    {
        //从声明中获取用户ID
        var userId = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier)?.Value;
        
        if (string.IsNullOrEmpty(userId))
        {
            return StatusCode(401, RequestResponse.BadRequest("无效的Token"));
        }

        var response = await _financeUserLoginService.ValidateFinanceUserToken(userId);
        return StatusCode(response.Status, response);
    }
}